package com.cskaoyan.shopping.service.impl;

import com.cskaoyan.mall.commons.exception.ExceptionProcessorUtils;
import com.cskaoyan.mall.constant.ShoppingRetCode;
import com.cskaoyan.mall.dto.*;
import com.cskaoyan.shopping.converter.ContentConverter;
import com.cskaoyan.shopping.converter.ProductConverter;
import com.cskaoyan.shopping.dal.entitys.Item;
import com.cskaoyan.shopping.dal.entitys.ItemDesc;
import com.cskaoyan.shopping.dal.entitys.Panel;
import com.cskaoyan.shopping.dal.entitys.PanelContentItem;
import com.cskaoyan.shopping.dal.persistence.*;
import com.cskaoyan.shopping.dto.AllProductRequest;
import com.cskaoyan.shopping.dto.AllProductResponse;
import com.cskaoyan.shopping.dto.PanelDto;
import com.cskaoyan.shopping.dto.RecommendResponse;
import com.cskaoyan.shopping.service.IProductService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ClassName: IProductServiceImpl
 * @Description:
 * @Author: 你猜
 * @Date: 2022/6/18 9:28
 */

@Service
public class IProductServiceImpl implements IProductService {

    private static final String ORDER_COLUMN = "price";
    private static final String ORDER_ASC = "asc";
    private static final String ORDER_DESC = "desc";
    private static final String ORDER_ID = "id";
    private static final Integer HOT_PRODUCT_POSITION = 1;

    @Autowired
    ItemMapper itemMapper;

    @Autowired
    ItemDescMapper itemDescMapper;

    @Autowired
    GoodsPanelMapper goodsPanelMapper;

    @Autowired
    GoodsPanelContentMapper goodsPanelContentMapper;

    @Autowired
    ProductConverter productConverter;

    @Autowired
    ContentConverter contentConverter;

    @Override
    public ProductDetailResponse getProductDetail(ProductDetailRequest request) {
        ProductDetailResponse productDetailResponse = new ProductDetailResponse();

        ProductDetailDto productDetailDto = new ProductDetailDto();
        productDetailDto.setProductId(request.getId());

        try {
            // 校验参数
            request.requestCheck();

            ItemDesc itemDesc = itemDescMapper.selectByPrimaryKey(request.getId());
            Item item = itemMapper.selectByPrimaryKey(request.getId());

            productDetailDto.setDetail(itemDesc.getItemDesc());
            productDetailDto.setLimitNum(item.getLimitNum().longValue());
            productDetailDto.setProductImageBig(item.getImageBig());
            productDetailDto.setProductImageSmall(Arrays.asList(item.getImages()));
            productDetailDto.setProductName(item.getTitle());
            productDetailDto.setSalePrice(item.getPrice());
            productDetailDto.setSubTitle(item.getSellPoint());

            productDetailResponse.setProductDetailDto(productDetailDto);
            productDetailResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            productDetailResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(productDetailResponse, e);
        }

        return productDetailResponse;
    }

    @Override
    public AllProductResponse getAllProduct(AllProductRequest request) {
        // 在执行查询之前，可以开启分页
        // sql语句预编译的过程给你拼接上分页的sql
        PageHelper.startPage(request.getPage(), request.getSize());

        AllProductResponse allProductResponse = new AllProductResponse();

        // cid可能为null，priceGt，priceLte可能为""，默认为全部显示
        try {
            // 参数校验
            request.requestCheck();

            List<Item> items = new ArrayList<>();
            // sort=1,价格从低到高排序；sort=-1，价格从高到低排序；=，综合排序
            if ("1".equals(request.getSort())) {
                items = itemMapper.selectItemFront(request.getCid(), ORDER_COLUMN, ORDER_ASC, request.getPriceGt(), request.getPriceLte());
            } else if ("-1".equals(request.getSort())) {
                items = itemMapper.selectItemFront(request.getCid(), ORDER_COLUMN, ORDER_DESC, request.getPriceGt(), request.getPriceLte());
            } else if ("".equals(request.getSort())) {
                // 指定排序顺序，默认按照id升序来排序
                items = itemMapper.selectItemFront(request.getCid(), ORDER_ID, ORDER_ASC, request.getPriceGt(), request.getPriceLte());
            }

            // 进行相应的分页
            PageInfo pageInfo = new PageInfo(items);

            // 数据类型转化
            List<ProductDto> productDtos = productConverter.items2Dto(items);

            allProductResponse.setProductDtoList(productDtos);
            allProductResponse.setTotal(pageInfo.getTotal());

            allProductResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            allProductResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());

        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(allProductResponse, e);
        }

        return allProductResponse;
    }

    @Override
    public RecommendResponse getRecommendGoods() {
        RecommendResponse recommendResponse = new RecommendResponse();
        Set<PanelDto> panelDtos = new LinkedHashSet<>();

        // 防止查询出错
        try {
            // 根据panel中的position来获取panelId
            List<Integer> panelIds = goodsPanelMapper.selectPanelIdByPostion(HOT_PRODUCT_POSITION);
            for (Integer panelId : panelIds) {
                // 根据id查出相应的panel信息
                List<Panel> panels = goodsPanelMapper.selectPanelContentById(panelId);

                for (Panel panel : panels) {
                    // 根据id查出panel的商品信息
                    List<PanelContentItem> panelContentItems = goodsPanelContentMapper.selectPanelContentAndProductWithPanelId(panelId);

                    // 类型转化
                    panel.setPanelContentItems(panelContentItems);
                    PanelDto panelDto = contentConverter.panel2Dto(panel);
                    panelDtos.add(panelDto);
                }
            }

            recommendResponse.setPanelContentItemDtos(panelDtos);
            recommendResponse.setCode(ShoppingRetCode.SUCCESS.getCode());
            recommendResponse.setMsg(ShoppingRetCode.SUCCESS.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            ExceptionProcessorUtils.wrapperHandlerException(recommendResponse, e);
        }

        return recommendResponse;
    }

    @Override
    public AllItemResponse getAllItems() {
        return null;
    }
}